package com.kong.configuration;


import org.burgeon.commons.runtime.ThreadContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import javax.servlet.http.Cookie;
import java.util.List;

@Controller
public class GlobalInterceptor implements HandlerInterceptor {


    private List<String> includePathPatterns = new ArrayList<>();
    private List<String> excludePathPatterns = new ArrayList<>();



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 token
        String token = request.getHeader(AppConst.tokenKey);
        if (!StringUtils.hasText(token)) {
            token = request.getParameter(AppConst.tokenKey);
        }
        if (!StringUtils.hasText(token)) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AppConst.tokenKey)) {
                        token = cookie.getValue();
                        break;
                    }
                }
            }
        }
        if (StringUtils.hasText(token)) {
            ThreadContextHolder.setToken(token);
        }

        // 2. 获取 request-uri
        String requestMethod = request.getMethod();
        String requestPath = request.getRequestURI();
        ThreadContextHolder.setRequestPath(requestMethod + ":" + requestPath);

        return true;
    }





    /**
     * 将要拦截的路径
     * @return
     */
    public List<String> getIncludePathPatterns() {
        return includePathPatterns;
    }

    /**
     * 排除拦截的路径设置
     * @return
     */
    public List<String> getExcludePathPatterns() {
        return excludePathPatterns;
    }


}